package sdu.icat.ltp.service;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import sdu.icat.ltp.api.LtpAPIConnectionFactory;
import sdu.icat.ltp.api.ResultCache;
import sdu.icat.ltp.api.TransElement;
import sdu.icat.ltp.persistant.AbstractPersistant;
import sdu.icat.ltp.persistant.MongoPersistant;
import sdu.icat.ltp.tool.DataBaseFascade;
import sdu.icat.ltp.tool.DataBaseFascade.Context;

/**
 * api接口
 * @author ljh_2015
 *
 */
public class ApiInService {

    private final Logger log = Logger.getLogger(ApiInService.class);
    private final ResultCache cache = ResultCache.newInstance();
    private final BlockingQueue<String> request = new LinkedBlockingQueue<>();
    private final int resetTime = 6000;
    private boolean status = false;
    private final int pull_Thread = 8;

    public void saveArticle() {
	DataBaseFascade.listArticle();
    }
    
    public List<Context> getContexts(String booktitle,String chaptertitle) {
	return DataBaseFascade.getContext(booktitle, chaptertitle);
    }
    
    public List<String> listArticle() {
	return DataBaseFascade.getArticleTitles();
    }
    
    public List<String> listChapter(String title) {
	return DataBaseFascade.getChapterlist(title);
    }
    

    /**
     * 存储数据
     * @param title 
     * @param text
     */
    public void saveEntity(String title,String text,int paragraph) {
	if(text.length()>0) {
	    TransElement element = LtpAPIConnectionFactory.buildText(text).openConnection();
	    if(element!=null) {
		cache.putElement(element,title,String.valueOf(paragraph));
	    } 
	}
    }

    public void saveEntity(String title,String text) {
	saveEntity(title,text,-1);
    }

    public void putEntity(String text) throws InterruptedException {
	log.info("put request: "+text);
	request.put(text);
    }

    /**
     * 存储简单原语句
     * @param text
     */
    public void saveSimpleEntity(String text) {
	//保证数据有长度
	if(text.length()>0) {
	    TransElement element = LtpAPIConnectionFactory.buildText(text.trim()).openConnection();
	    if(element!=null) {
		cache.putElement(element);
	    } 
	}
    }

    public synchronized void saveSimpleArticle(String atitle,String ctitle,int sort,String text) {
	if(text.length()>0) {
	    TransElement element = LtpAPIConnectionFactory.buildText(text.trim()).openConnection();
	    if(element!=null) {
		element.setBaseName(atitle);
		element.setTitle(ctitle);
		element.setParagraph(sort);
		cache.putElement(element);
	    } 
	}
    }

    /**
     * 批量存储
     */
    public void saveManyEntities(String title,List<String> texts,int paragraph) {
	for(String text:texts) {
	    saveEntity(title, text,paragraph);
	}
    }

    /**
     * 启动服务
     */
    public void start() {
	status = true;
	//多个线程并发处理消息
	for(int i=0;i<pull_Thread;i++) {
	    new Thread(new PullService(new MongoPersistant())).start();
	}
	new Thread(new RequestService()).start();
    }

    /**
     * 关闭服务
     */
    public void close() {
	status = false;
    }

    public boolean status() {
	return status;
    }


    class PullService implements Runnable {

	private AbstractPersistant abPersistant;
	
	public PullService(AbstractPersistant abPersistant) {
	    this.abPersistant = abPersistant;
	}

	@Override
	public void run() {
	    int count = 0;
	    log.info("start PullService");
	    while(status) {
		TransElement element = cache.pollElement();
		if(element!=null) {
		    abPersistant.persistant(element);
		    count++;
		}
	    }
	    log.info("close PullService succ,complete "+count+" element pull");
	}
    }

    class RequestService implements Runnable {

	@Override
	public void run() {
	    int count = 0;
	    int reset = 0;
	    log.info("start RequestService");
	    while(status) {
		try {
		    String requestText = request.poll(2, TimeUnit.SECONDS);
		    if(requestText!=null) {
			String[] request = requestText.split("&space"); 
			if(request.length==1) {
			    log.debug("get request is "+requestText);
			    saveSimpleEntity(requestText);
			} else if(request.length==2){
			    log.debug("get request the title is "+request[0]+" and the text is "+request[1]);
			    saveEntity(request[0], request[1]);
			} else if(request.length==3){
			    log.debug("get request "+request[2]+" the title is "+request[0]+" and the text is "+request[1]);
			    saveEntity(request[0], request[1],Integer.parseInt(request[2]));
			} else {
			    log.error("parameters has error "+requestText);
			    continue;
			}
			count++;
			reset = 0;

		    } else {
			if(reset>=resetTime) {
			    break;
			}
			reset++;
		    }
		    Thread.sleep(50);
		} catch (InterruptedException e) {
		    log.error(e.getMessage());
		}
	    }
	    log.info("close requestService succ,complete "+count+" request send");
	}

    }
}
